package com.cloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloud.config.SecurityCloudConfig;
import com.cloud.config.exception.BusinessException;
import com.cloud.entity.ResultEntity;
import com.cloud.entity.ResultPageEntity;
import com.cloud.dao.UploadFileDao;
import com.cloud.entity.UploadFileEntity;
import com.cloud.service.MediaService;
import com.cloud.service.UploadFileService;
import com.cloud.util.CommonUtil;
import com.cloud.util.MediaUtil;
import com.cloud.util.StringUtil;
import com.cloud.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.cloud.util.UploadUtil.renameFiles;

/**
 * @author: cansong
 * @date: 2020/11/24 9:00
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private UploadFileDao uploadFileDao;

    @Autowired
    private MediaService mediaService;

    @Autowired
    private SecurityCloudConfig securityCloudConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity uploadFile(MultipartFile multipartFile) throws IOException {
        UploadFileEntity entity = multipartFileToFileEntity(multipartFile);
        ResultEntity resultEntity = saveAndConvert(multipartFile, entity);
        if (resultEntity.isSuccess()) {
            return addUploadFile(entity);
        }
        return resultEntity;
    }

    @Override
    public ResultEntity saveAndConvert(MultipartFile multipartFile, UploadFileEntity entity) throws IOException {
        if (!multipartFile.isEmpty()) {
            String fileName = entity.getFileName();
            String srcFilePath = securityCloudConfig.getFileRoot() + securityCloudConfig.getFilePath() + fileName;
            File file = new File(srcFilePath);
            if(file.exists()){
                return CommonUtil.errorResult(ErrorEnum.E_100001);
            }else{
                multipartFile.transferTo(file);
                if (MediaUtil.isVideoFile(fileName) && MediaUtil.isInConvertList(MediaUtil.getFileSuffix(fileName))) {
                    String destFileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "mp4";
                    String destFilePath = securityCloudConfig.getFileRoot() + securityCloudConfig.getFilePath() + destFileName;
                    File dest = new File(destFilePath);
                    if(dest.exists()){
                        return CommonUtil.errorResult(ErrorEnum.E_100001);
                    }
                    MediaUtil.CommonConvert(securityCloudConfig.getFfmepgPath(), srcFilePath, destFilePath);
                    entity.setConvertedMediaType("mp4");
                }
                return CommonUtil.successResult("文件上传成功");
            }
        }
        return CommonUtil.errorResult(ErrorEnum.E_100002);
    }

    @Override
    public UploadFileEntity multipartFileToFileEntity(MultipartFile multipartFile) throws IOException {
        UploadFileEntity entity = new UploadFileEntity();
        if (!multipartFile.isEmpty()) {
            entity.setFileName(multipartFile.getOriginalFilename().replaceAll(" ", ""));
            entity.setFileType(MediaUtil.isImageFile(multipartFile.getOriginalFilename()) ? "2" : "1");
            entity.setFilePath(securityCloudConfig.getFileRoot() + securityCloudConfig.getFilePath());
            entity.setFileSize(Integer.valueOf(String.valueOf(multipartFile.getSize())));
            entity.setCheckSum(DigestUtils.md5DigestAsHex(multipartFile.getBytes()));
        }
        return entity;
    }

    /**
     * @param entity
     * @return
     * @description 新增
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity addUploadFile(UploadFileEntity entity) {
        uploadFileDao.addUploadFile(entity);
        return CommonUtil.successResult(entity);
    }

    /**
     * @param
     * @return
     * @description 新增(多)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity addUploadFiles(List<UploadFileEntity> entityList) {
        for (UploadFileEntity entity : entityList) {
            addUploadFile(entity);
        }
        return CommonUtil.successResult(entityList);
    }

    /**
     * @param jsonObject
     * @return
     * @description 查询
     */
    @Override
    public ResultPageEntity listUploadFile(JSONObject jsonObject) {
        CommonUtil.fillPageParam(jsonObject);
        int count = uploadFileDao.countUploadFile(jsonObject);
        List<JSONObject> list = uploadFileDao.listUploadFile(jsonObject);
        return CommonUtil.successResultPage(jsonObject, list, count);
    }

    /**
     * @param entity
     * @return
     * @description 删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity removeUploadFile(UploadFileEntity entity) {
        uploadFileDao.removeUploadFile(entity);
        return CommonUtil.successResult();
    }

    /**
     * @param uploadFileEntityList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity uploadNotify(List<UploadFileEntity> uploadFileEntityList) {
        for (UploadFileEntity fileEntity : uploadFileEntityList) {
            File mediaFile = new File(fileEntity.getFilePath());
            String mediaType = StringUtil.getFileNameSuffix(mediaFile.getName());
            if (mediaType != null) {
                mediaType = mediaType.toLowerCase();
            }
            // 如果是 avi,flv,mkv,mov,wmv 文件, 转换为 mp4
            if (MediaUtil.isInConvertList(mediaType)) {
                String destFilePath = mediaService.convertMediaFile(mediaFile.getAbsolutePath(), mediaType, MediaUtil.MEDIA_MP4);
                if (destFilePath == null) {
                    throw new BusinessException(String.format("媒体文件: %s 转换失败", mediaFile.getAbsolutePath()));
                } else {
                    fileEntity.setConvertedMediaType(MediaUtil.MEDIA_MP4);
                }
            }
        }
        return addUploadFiles(uploadFileEntityList);
    }

    /**
     * 条件查询
     *
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity getUploadFileByCondition(JSONObject jsonObject) {
        List<JSONObject> files = uploadFileDao.getUploadFileByCodition(jsonObject);
        return CommonUtil.successResult(files);
    }
}
